#导入请求包
import requests
#导入json包
import json
#设置要访问的地址（这里是get请求）


#获取歌曲评论url
url = 'http://musicapi.leanapp.cn/comment/music' 
#歌曲id
id = 1391891631 


#普通评论
def getCommentsJson(api_url, music_id, limit, offs):
    json_str = requests.get(api_url, params = {'id': music_id,'limit': limit, 'offset': offs})
    return json_str


#热评
def getHotCommentsJson(api_url, music_id):
    json_str = requests.get(api_url, params = {'id': music_id,'limit': 50})
    return json_str


def writeFile(filename, test_url, test_id, total, page_limit, page_offset):
    with open(filename, "w", encoding='utf-8') as file: 
        while total > page_offset:
            #热评json提取评论信息
            hot_result = json.loads(getHotCommentsJson(test_url, test_id).text)
            hotComments = hot_result['hotComments']
            msg_list = []
            if (len(hotComments) == 0):
                page_offset = total
                break
            for hot in hotComments:
                user = hot['user']
                nickname = user['nickname']
                content = hot['content']
                likedCount = hot['likedCount']
                message = ' --- ' + nickname + ' --- \n\n' + content + '\n\n赞:' + str(likedCount) + '\n\n'
                msg_list.append(message)
            for msg in msg_list:
                file.write(msg)
            total = total - len(msg_list)
            if total <= 0:
                break
            result_json = json.loads(getCommentsJson(test_url, test_id, page_limit, page_offset).text)
            if (result_json['code'] != 200):
                page_offset = total
                break
            comments = result_json['comments']

            #普通评论json提取评论信息 
            msg_list = []
            if (len(comments) == 0):
                page_offset = total
                break
            for comment in comments:
                user = comment['user']
                nickname = user['nickname']
                content = comment['content']
                likedCount = comment['likedCount']
                message = ' --- ' + nickname + ' --- \n\n' + content + '\n\n赞:' + str(likedCount) + '\n\n'
                msg_list.append(message)
            for msg in msg_list:
                file.write(msg)
            page_offset = page_offset + page_limit
            if page_offset > 0:
                print('以获取%d条', page_offset)


def main():
    print('\n_____________到点了____________\n')
    print('\n歌曲id可以从歌曲的分享链接获取\n')
    print('\n如周杰伦《安静》的分享链接中https://music.163.com/#/song?id=186139  ，该id即为输入id\n\n')
    test_url = url
    page_limit = 50
    page_offset = 0
    test_id_str = input("请输入歌曲id:")
    test_id = test_id_str.strip()
    music_name = input("请输入歌曲名（文件名）:")
    total_str = input("请输入想要获取评论数量(大概数量，不太准确):")
    total = int(total_str.strip())
    have_next = input("输入Y继续，输入N退出:")
    if have_next.lower() == 'y':
        filename = music_name + '.txt'
        # test_id = 185924
        # test_url = url
        # page_limit = 50
        # page_offset = 0
        # total = 50
        # filename = 'test.txt'
        print('\n_____________整____________\n')
        if total < page_limit:
            page_limit = total
        writeFile(filename, test_url, test_id, total, page_limit, page_offset)
        print('\n_____________end____________\n')
    else:
        print('\n_____________不整了____________\n')
        print('\n_____________end____________\n')

if __name__ == '__main__':
    main()
